using AutoMapper;
using B.S.NewMedical.Api.Write.Application.Command.User;
using B.S.NewMedical.Domain.User;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.NewMedical.Api.Write.Application.Handler.User
{
    /// <summary>
    /// 获取用户列表处理器
    /// </summary>
    public class GetUserListHandler : IRequestHandler<GetUserListCommand, ApiResult<List<UserDto>>>
    {
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetUserListHandler> _logger;

        public GetUserListHandler(
            IBaseRepository<UserModel> userRepository,
            IMapper mapper,
            ILogger<GetUserListHandler> logger)
        {
            _userRepository = userRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiResult<List<UserDto>>> Handle(GetUserListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var query = _userRepository.GetAll().Where(u => !u.IsDeleted);

                // 应用搜索条件
                if (!string.IsNullOrWhiteSpace(request.SearchKeyword))
                {
                    query = query.Where(u => u.Username.Contains(request.SearchKeyword) || 
                                           u.RealName.Contains(request.SearchKeyword));
                }

                // 应用用户类型过滤
                if (!string.IsNullOrWhiteSpace(request.UserType))
                {
                    // 将字符串用户类型转换为对应的数字类型
                    int? userTypeInt = request.UserType switch
                    {
                        "医生" => 1,
                        "护士" => 2,
                        "管理员" => 3,
                        "药房管理员" => 4,
                        "收费员" => 5,
                        _ => null
                    };
                    
                    if (userTypeInt.HasValue)
                    {
                        query = query.Where(u => u.Type == userTypeInt.Value);
                    }
                }

                var users = query.OrderBy(u => u.CreateTime).ToList();

                // 映射到DTO
                var userDtos = users.Select(u => new UserDto
                {
                    UserId = u.Id,
                    Username = u.Username,
                    RealName = u.RealName,
                    Type = u.Type
                }).ToList();

                _logger.LogInformation("成功获取用户列表，共{Count}个用户", userDtos.Count);

                return new ApiResult<List<UserDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取用户列表成功",
                    Data = userDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户列表时发生异常");
                return new ApiResult<List<UserDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取用户列表失败：" + ex.Message
                };
            }
        }
    }
} 